package com.example.websocket.another.service;

import com.example.websocket.another.component.WebSocketSendAsync;
import com.example.websocket.another.config.ThreadPoolTaskConfig;
import com.example.websocket.another.dto.NotifyBean;
import com.example.websocket.another.dto.UserVo;
import com.example.websocket.another.entity.UserMessageEntity;
import com.example.websocket.another.mapper.UserMapper;
import com.example.websocket.another.mapper.UserMessageMapper;
import com.example.websocket.another.utils.SocketMessageUtil;
import com.example.websocket.another.web.WebSocketController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@Service
@Slf4j
public class UserMessageService {

    @Autowired
    private UserMessageMapper userMessageMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketSendAsync webSocketSendAsync;
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;
    @Autowired
    private UserService userService;


    @Async(ThreadPoolTaskConfig.TASK_EXECUTOR_NAME)
    public void saveAllMissMessage(UserVo userVo) {
        //所有用户
        List<Long> usersId = userMapper.getAllUserId();
        //在线用户
        LinkedList<Long> allUserOnline = webSocketSendAsync.getAllUserOnline();
        if (allUserOnline != null && allUserOnline.size() > 0) {
            //剩下所有不在线用户
            usersId.removeAll(allUserOnline);
        }

        usersId.forEach(id -> {
            if (id != WebSocketController.ADMIN) {
                UserMessageEntity messageEntity = UserMessageEntity.builder()
                        .sendTo(id)
                        .message(userVo.getMessage())
                        .senderFrom(Long.parseLong(userVo.getFrom()))
                        .createTime(new Date())
                        .topic(1).build();
                userMessageMapper.insertUserMessage(messageEntity);
            }
        });

    }

    @Async(ThreadPoolTaskConfig.TASK_EXECUTOR_NAME)
    @Transactional(rollbackFor = Exception.class)
    public void sendToThisConnectUserMessage(Long userId, String sessionId) {
        log.info("给重新登陆的 离线用户发消息---》{} ,sessionID:{}" + userId, sessionId);
        List<UserMessageEntity> messageEntityList = userMessageMapper.getUserMessageBySendTo(userId);
        messageEntityList.forEach(messageEntity -> {
            NotifyBean notifyBean2 = NotifyBean.builder().content("离线消息：" + messageEntity.getMessage()).sender(userService.getUserName(messageEntity.getSenderFrom() + "")).build();
            simpMessagingTemplate.convertAndSendToUser(sessionId, WebSocketController.WEB_SC_TOPIC_NOTIFY, notifyBean2, SocketMessageUtil.createHeaders(sessionId));
            log.info("离线消息发送成功！");
            userMessageMapper.deleteMes(messageEntity.getId());
        });
    }
}
